const app = getApp()
const util = require('../../../../utils/util.js')
import * as echarts from '../../../components/ec-canvas/echarts'
let lineChart = null
let lineOption = {
  color: ['#37a2da', '#32c5e9', '#67e0e3'],
  grid: {
    left: '22px',
    right: '0',
    bottom: '0',
    top: '30px',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: true,
    axisLine: { show: false },
    axisTick: { show: false },
    axisLine: {
      lineStyle: {
          color: '#e6ecf8',
          width: '1',
      }
  },
  axisLabel: {
    textStyle: {
        color: '#858b9c',
        fontSize: 10
    }
  },
    data: []
  },
  yAxis: {
    x: 'center',
    name: '',
    nameTextStyle: {
      color: "#858B9C",
      fontSize: 10
    },
    type: 'value',
    axisLabel: {
      textStyle: { color: 'rgba(0, 0, 0, 0.65)', fontSize: 10 }
    },
    axisLine: { show: false },
    axisTick: { show: false },
    splitLine: {
      show: true,
      lineStyle: { color: '#E6ECF8' }
    }
  },
  series: [
    {
      type: 'line',
      symbol: 'none', // 拐点的样式，还可以取值'rect','angle'等
      symbolSize: 8, // 拐点的大小
      lineStyle: {
        normal: {
            width: 2,
            color: '#4661F4',
        }
    },
    smooth: false,
    areaStyle: {
      normal: {
        color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
          { offset: 0, color: "#fff" },
          { offset: 1, color: "#4661F4" }
        ])
      }
    },
     data: [],
    }
  ]
}
let funnelChart = null
let funnelOption = {
  color: ['#2859FE', '#3A92FE', '#619AD1', '#20D97B', '#FFC000'],
  grid: {
    left: '0',
    right: '0',
    bottom: '0',
    top: '0',
    containLabel: true
  },
  series: [{
    top: '0',
    type: 'funnel',
    width: '51%',
    height: '100%',
    gap: 0,
    left: '12px',
    label: {
        show: true,
        position: 'inside',
        fontSize: '10',
        formatter: '{c}%',
    },
    itemStyle: {
      borderWidth: 0,
    },
    data: [{value: 100, name: '学习主页'}, {value: 60, name: '课程详情页'}, {value: 40, name: '章节详情页'}, {value: 20, name: '演练详情页'}, {value: 10, name: '通关详情页'}]
  },
  {
    top: '0',
    type: 'funnel',
    width: '51%',
    height: '100%',
    gap: -1,
    left: '12px',
    z: 2,
    itemStyle: {
      borderWidth: 0,
    },
    label: { //饼图图形上的文本标签      
      show: true, //默认展示
      color: "#fff" ,
      position: "outside", //默认'outside'饼图扇区外侧，通过视觉引导线连到相应的扇区
      formatter: function (pram) {
          console.log(pram);
        // var arr = [];
        // // arr.push('{name|'+pram.name+':'+pram.value+'}')
        // arr.push('{name|' + pram.name + '}{bb|' + d.value + '人}')
        // return arr.join('');
        var ins = '{aa|' + pram.name+':'+ '}{bb|' + pram.value + '人}';
        return ins
    },
    backgroundColor: "auto", //圆点颜色，auto：映射的系列色
    // height,width,lineHeight必须为0
    height: 0,
    width: 0,
    lineHeight: 0,
    // radius和padding为圆点大小，圆点半径为几radius和padding各项数值就为几如：圆点半径为1
    borderRadius: 4,
    padding: [4, -4, 4, -4],
    rich: { // 自定义富文本样式
      aa: {
          color: '#858B9C',
          padding: [-3, 0, 0, 10],
          align: 'left',
      },
      bb: {
          align: 'left',
          color: '#41485D',
          width: 55,
          fontWeight: 'bold',
          padding: [-3,0, 0, 10]
      }
    },
  },
    labelLine: {
      length: 30,
      lineStyle: {
          width: 1,
          type: 'solid',
      }
    },
    data: [{value: 100, name: '学习主页'}, {value: 60, name: '课程详情页'}, {value: 40, name: '章节详情页'}, {value: 20, name: '演练详情页'}, {value: 10, name: '通关详情页'}]
  }
]}
let categoryChart = null
let categoryOption = {
  grid: {
    left: '22px',
    right: '62px',
    bottom: '0',
    top: '0',
    containLabel: true
  },
  yAxis: {
    type: 'category',
    min: 0.01,
    axisTick: { show: false },
    axisLine: {
      lineStyle: {
          color: '#e6ecf8',
          width: '1',
      }
    },
    axisLabel: {
      textStyle: {
          color: '#41485d',
          fontSize: 10
      }
    },
    data: ['通关详情页', '演练详情页', '学习详情页', '场景列表页', '训练主页']
  },
  xAxis: {
    show: false
  },
  series: [{
    data:[
      {
        value:2,
        itemStyle:{
          normal:{color:'#52CCA3'}
      }
      }, 
      {
        value:3,
        itemStyle:{
          normal:{color:'#69EEC2'}
      }
      },
      {
        value:3,
        itemStyle:{
          normal:{color:'#C2F7E5'}
      }
      },
      {
        value:0,
        itemStyle:{
          normal:{color:'#69EEC2'}
      }
      },
      {
        value:8,
        itemStyle:{
          normal:{color:'#5DCFA9'}
      }
      }
      ],
      type: 'bar',
      barWidth: 17,
      barGap:'30%',
      barCateGoryGap:'30%',
      label: {
        show: true,
        position: 'right', 
        distance: 40, 
        align: 'right', 
        formatter: function (params) {
          console.log(params)
            return params.value + '人';
        },
        color: '#41485d',
        fontSize: 12,
      },
      showBackground: true,
      backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
      }
  }]
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    isSceneSort:false,
    trainInfo:{},
    sortList:[
       {name:'按最后学习时间倒序',sortField:'lastTime',sortType:'desc'},
       {name:'按最后学习时间正序',sortField:'lastTime',sortType:'asc'}
    ],
    sortShow:false,
    list: [],
    sceneList: [],
    orgId: app.globalData.userInfo.orgId,
    studyFields:[
      {
        prop: 'userName',
        label: '姓名',
        width: '250'
      },
      {
        prop: 'levelFourOrgName',
        label: '所属组织',
        width: '220'
      },
      {
        prop: 'lastTime',
        label: '最后学习时间',
        width: '220'
      },
    ],
    trainFields:[
      {
        prop: 'userName',
        label: '姓名',
        width: '250'
      },
      {
        prop: 'levelFourOrgName',
        label: '所属组织',
        width: '220'
      },
      {
        prop: 'lastTime',
        label: '最后训练时间',
        width: '220'
      },
    ],
    examFields:[
      {
        prop: 'name',
        label: '考试主题',
        width: '200'
      },
      {
        prop: 'enterNum',
        label: '实际参与',
        width: '200'
      },
      {
        prop: 'coachingNum',
        label: '计划参与',
        width: '200'
      },
    ],
    sceneFields: [{
      prop: 'sceneName',
      label: '场景名称',
      width: '220'
    },
    {
      prop: 'personNum',
      label: '访问人数',
      width: '150'
    },
    {
      prop: 'num',
      label: '访问次数',
      width: '150'
    },
    {
      prop: 'avgDuration',
      label: '平均训练时长',
      width: '230'
    }],
    total: 0,
    // startdate: (util.timestampToTime(Date.now() - 7 * 60 * 60 * 24 * 1000)),
    // enddate: (util.timestampToTime(Date.now() - 0 * 60 * 60 * 24 * 1000)),
    // 后端只造了当月第一天的数据，暂时先用这个
    startdate: (util.timestampToTime(new Date().setDate(1))),
    enddate: (util.timestampToTime(new Date().setDate(1))),
    selectIndex: '0',
    navBarHeight: app.globalData.navBarHeight,
    bankList: [],
    bankidList: [],
    bankindex: '',
    branchList: [],
    branchidList: [],
    branchidindex: '',
    subBranchList: [],
    subBranchidList: [],
    subBranchindex: '',
    siteList: [],
    siteidList: [],
    siteindex: '',
    selectlist: [{name: '银行', num: 500, active: false}, {name: '分行', num: 500, active: false}, {name: '支行', num: 10000, active: false}, {name: '网点', num: 10000, active: false}],
    tablist: [],
    setTitleName: '活跃数',
    sortField: '',
    type: '',
    typeName: '',
    bannerInfo: '',
    activityBoardTrendRespList: '',
    hasFixed: false,
    scenehasFixed: false,
    queryForm: { levelOneOrgId: '', levelTwoOrgId: '', levelThreeOrgId: '', levelFourOrgId: '', startDate: '', endDate: '', indexType: 'activityNum' },
    query: { bankName: '', bankBranchName: '', bankSubBranchName: '', bankWorkstationName: '' },
    params: { parentId: ''},
    currentPage:1,
    ecTrend: {
      onInit: function (canvas, width, height, dpr) {
        lineChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(lineChart);
        lineChart.setOption(lineOption);
        return lineChart;
      }
    },
    ecFlow: {
      onInit: function (canvas, width, height, dpr) {
        funnelChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(funnelChart);
        funnelChart.setOption(funnelOption);
        return funnelChart;
      }
    },
    ecCategory: {
      onInit: function (canvas, width, height, dpr) {
        categoryChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(categoryChart);
        categoryChart.setOption(categoryOption);
        return categoryChart;
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, lineOption.series[0])
    wx.setNavigationBarTitle({
      title: options.typeName,
    })
    let queryForm = JSON.parse(options.queryForm)
    let queryIndex = JSON.parse(options.queryIndex)
    console.log(queryIndex, queryForm.roleType)
    // let fields = JSON.parse(options.fields)
    const type = options.type
    console.log(type,'type');
    let fields = type === 'study'?this.data.studyFields:type === 'training'?this.data.trainFields:this.data.examFields
    this.setData({
      queryForm: queryForm,
      startdate: queryForm.startDate,
      enddate: queryForm.endDate,
      fields: fields,
      type: options.type,
      hasFixed: (options.type === 'study' || options.type === 'training') ? true : false,
      typeName: options.typeName,
      bankindex: queryIndex.bankindex,
      branchidindex: queryIndex.branchidindex,
      subBranchindex: queryIndex.subBranchindex,
      siteindex: queryIndex.siteindex,
    })
    console.log(this.data.bankindex)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log(this.data.typeName,'typeName');
    const {typeName} = this.data
    if(typeName === '学习'){
      this.getStudyStatus()
      this.getStudyTrend()
      this.getStudyDetail()
    }else if (typeName === '训练'){
      this.setData({
        sortList:[
          {name:'按最后训练时间倒序',sortField:'lastTime',sortType:'desc'},
          {name:'按最后训练时间正序',sortField:'lastTime',sortType:'asc'}
       ],
      })
      this.getTrainStatus()
      this.getTrainTrend()
      this.getTrainDetail()
      this.getTrainSceneList()
    }else if(typeName === '考试'){

    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.queryForm.roleType === 'admin') {
      this.getAdminOrgList()
    } else {
      this.getAllBankList()
    }
    if (this.data.typeName === '考试') {
      this.getTrainActiveList()
    }
    if (this.data.queryForm.levelOneOrgId) {
      this.defaultBranch()
    }
    if (this.data.queryForm.levelTwoOrgId) {
      this.defaultSubBranch()
    }
    if (this.data.queryForm.levelThreeOrgId) {
      this.defaultSite()
    }
  },
  // 页面上拉触底事件（上拉加载更多）
  onReachBottom: function () {
    const {typeName} = this.data
    let _currentPage = this.data.currentPage
    _currentPage++
    this.setData({
      currentPage:_currentPage
    })
    if(typeName === '学习'){
      this.getStudyDetail()
    }else if (typeName === '训练'){
      this.getTrainDetail()
      this.getTrainSceneList()
    }else if(typeName === '考试'){
      this.getTrainActiveList()
    }
 },
  // 自定义排序 
  sortHandle (e) {
    const _type = e.currentTarget.dataset.type
    const { type,selectIndex } = this.data
    if(_type && _type === 'scene'){
      this.setData({
        sortList:[
          {name:'按访问人数倒序',sortField:'userNum',sortType:'desc'},
          {name:'按访问人数正序',sortField:'userNum',sortType:'asc'},
          {name:'按访问次数倒序',sortField:'num',sortType:'desc'},
          {name:'按访问次数正序',sortField:'num',sortType:'asc'},
          {name:'按平均训练时长倒序',sortField:'avgDuration',sortType:'desc'},
          {name:'按平均训练时长正序',sortField:'avgDuration',sortType:'asc'}
        ],
        isSceneSort:true
      })
    }else{
      this.sortListChange(type,selectIndex)
      this.setData({
        isSceneSort:false
      })
    }
    this.setData({sortShow:true})
  },
  sortSelect (e) {
    const index = e.detail
    const item = this.data.sortList[index]
    const postData = {
      sortField:item.sortField,
      sortType:item.sortType
    }
    const { type,isSceneSort } = this.data
    if(type === 'study'){
      this.getStudyDetail(postData)
    }else if (type === 'training' && !isSceneSort){
      this.getTrainDetail(postData)
    }else{
      this.getTrainSceneList(postData)
    }
  },
  toggleBanner (e) {
    let id = e.currentTarget.dataset.id
    this.setData({
      selectIndex: id
    })
    const { type,selectIndex } = this.data
    this.sortListChange(type,selectIndex).then(()=>{
      if(type === 'study'){
        this.getStudyTrend()
        this.studyFieldsChange() // 变更表格字段
      }else if (type === 'training'){
        this.getTrainTrend()
        this.trainFieldsChange() // 变更表格字段
      }
    })
    
  },
  sortListChange (type,selectIndex) {
    return new Promise((resolve,reject)=>{
      if(type === 'study'){
        if(selectIndex === '0'){
          this.setData({
            sortList:[
              {name:'按最后学习时间倒序',sortField:'lastTime',sortType:'desc'},
              {name:'按最后学习时间正序',sortField:'lastTime',sortType:'asc'}
            ]
          })
        }else if(selectIndex === '1'){
          this.setData({
            sortList:[
              {name:'按学习次数倒序',sortField:'num',sortType:'desc'},
              {name:'按学习次数正序',sortField:'num',sortType:'asc'},
              {name:'按最后学习时间倒序',sortField:'lastTime',sortType:'desc'},
              {name:'按最后学习时间正序',sortField:'lastTime',sortType:'asc'}
            ]
          })
        }else{
          this.setData({
            sortList:[
              {name:'按完成课程数倒序',sortField:'completedCourses',sortType:'desc'},
              {name:'按完成课程数正序',sortField:'completedCourses',sortType:'asc'},
            ]
          })
        }
        resolve()
      }else if (type === 'training'){
        if(selectIndex === '0'){
          this.setData({
            sortList:[
              {name:'按最后训练时间倒序',sortField:'lastTime',sortType:'desc'},
              {name:'按最后训练时间正序',sortField:'lastTime',sortType:'asc'}
            ]
          })
        }else if(selectIndex === '1'){
          this.setData({
            sortList:[
              {name:'按训练次数倒序',sortField:'num',sortType:'desc'},
              {name:'按训练次数正序',sortField:'num',sortType:'asc'},
              {name:'按最后训练时间倒序',sortField:'lastTime',sortType:'desc'},
              {name:'按最后训练时间正序',sortField:'lastTime',sortType:'asc'}
            ]
          })
        }else if(selectIndex === '2'){
          this.setData({
            sortList:[
              {name:'按演练均分倒序',sortField:'drillAvgScore',sortType:'desc'},
              {name:'按演练均分正序',sortField:'drillAvgScore',sortType:'asc'},
            ]
          })
        }else{
          this.setData({
            sortList:[
              {name:'按通关均分倒序',sortField:'clearanceAvgScore',sortType:'desc'},
              {name:'按通关均分正序',sortField:'clearanceAvgScore',sortType:'asc'},
            ]
          })
        }
        resolve()
      }
    })
    
    
  },
  studyFieldsChange () {
    const {selectIndex} = this.data
    if(selectIndex === '0'){
      const studyFields = [{
        prop: 'userName',
        label: '姓名',
        width: '250'
      },
      {
        prop: 'levelFourOrgName',
        label: '所属组织',
        width: '220'
      },
      {
        prop: 'lastTime',
        label: '最后学习时间',
        width: '220'
      },]
      this.setData({
        fields:studyFields,
        hasFixed:false
      })
    }else if (selectIndex === '1'){
      const studyFields = [{
        prop: 'userName',
        label: '姓名',
        width: '250'
      },
      {
        prop: 'levelFourOrgName',
        label: '所属组织',
        width: '220'
      },
      {
        prop: 'num',
        label: '学习次数',
        width: '220'
      },
      {
        prop: 'lastTime',
        label: '最后学习时间',
        width: '220'
      },]
      this.setData({
        fields:studyFields,
        hasFixed:true
      })
    }else{
      const studyFields = [{
        prop: 'userName',
        label: '姓名',
        width: '250'
      },
      {
        prop: 'levelFourOrgName',
        label: '所属组织',
        width: '220'
      },
      {
        prop: 'completedCourses',
        label: '完成课程数',
        width: '220'
      }
      ]
      this.setData({
        fields:studyFields,
        hasFixed:false
      })
    }
  },
  trainFieldsChange () {
    const {selectIndex} = this.data
    if(selectIndex === '0'){
      const trainFields = [{
        prop: 'userName',
        label: '姓名',
        width: '250'
      },
      {
        prop: 'levelFourOrgName',
        label: '所属组织',
        width: '220'
      },
      {
        prop: 'lastTime',
        label: '最后训练时间',
        width: '220'
      },]
      this.setData({
        fields:trainFields,
        hasFixed:false
      })
    }else if (selectIndex === '1'){
      const trainFields = [{
        prop: 'userName',
        label: '姓名',
        width: '250'
      },
      {
        prop: 'levelFourOrgName',
        label: '所属组织',
        width: '220'
      },
      {
        prop: 'trainingNum',
        label: '训练次数',
        width: '220'
      },
      {
        prop: 'lastTime',
        label: '最后训练时间',
        width: '220'
      },]
      this.setData({
        fields:trainFields,
        hasFixed:true
      })
    }else if(selectIndex === '2'){
      const trainFields = [{
        prop: 'userName',
        label: '姓名',
        width: '250'
      },
      {
        prop: 'levelFourOrgName',
        label: '所属组织',
        width: '220'
      },
      {
        prop: 'drillAvgScore',
        label: '演练均分',
        width: '220'
      }
      ]
      this.setData({
        fields:trainFields,
        hasFixed:false
      })
    }else{
      const trainFields = [{
        prop: 'userName',
        label: '姓名',
        width: '250'
      },
      {
        prop: 'levelFourOrgName',
        label: '所属组织',
        width: '220'
      },
      {
        prop: 'clearanceAvgScore',
        label: '通关均分',
        width: '220'
      }
      ]
      this.setData({
        fields:trainFields,
        hasFixed:false
      })
    }
  },
  defaultBranch () {
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: {parentId: this.data.queryForm.levelOneOrgId}
    }).then(res => {
      if (res.length > 0) {
        this.data.branchList = []
        this.data.branchidList = []
        res.map(item => {
            this.data.branchList.push(item.orgName)
            this.data.branchidList.push(item.id)
          })
      }
      this.setData({
        branchList: this.data.branchList,
        branchidList: this.data.branchidList,
      })
    })
  },
  defaultSubBranch () {
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: {parentId: this.data.queryForm.levelTwoOrgId}
    }).then(res => {
      if (res.length > 0) {
        this.data.subBranchList = []
        this.data.subBranchidList = []
        res.map(item => {
            this.data.subBranchList.push(item.orgName)
            this.data.subBranchidList.push(item.id)
          })
      }
      this.setData({
        subBranchList: this.data.subBranchList,
        subBranchidList: this.data.subBranchidList
      })
    })
  },
  defaultSite () {
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: {parentId: this.data.queryForm.levelThreeOrgId}
    }).then(res => {
      if (res.length > 0) {
        this.data.siteList = []
        this.data.siteidList = []
        res.map(item => {
            this.data.siteList.push(item.orgName)
            this.data.siteidList.push(item.id)
          })
      }
      this.setData({
        siteList: this.data.siteList,
        siteidList: this.data.siteidList
      })
    })
  },
  getStudyStatus () {
    const params = this.data.queryForm
    app.api.post({
      url: 'qryStudyToTalNum',
      data: params
    }).then(res=>{
      console.log(res,'=====');
      this.setData({
        bannerInfo:res || {}
      })
    })
  },
  getTrainStatus () {
    const params = this.data.queryForm
    app.api.post({
      url: 'qryTrainingToTalNum',
      data: params
    }).then(res=>{
      console.log(res,'=====');
      this.setData({
        trainInfo:res || {}
      })
    })
  },
  getTrainTrend () {
    let params = this.data.queryForm
    const {selectIndex , type } = this.data
    let url = ''
    if(selectIndex === '0'){
        url = 'qryTrainingTrend'
        params = {...this.data.queryForm,appFlag:1}
    }else if (selectIndex === '1'){
        url = 'qryTrainingNumTrend'
    }else if(selectIndex === '2'){
        url = 'qryTrainingDrillAvgScoreTrend'
    }else{
        url = 'qryTrainingClearanceAvgScoreTrend'
    }
    app.api.post({
      url: url,
      data: params
    }).then(res=>{
      console.log(res,'=====');
      const trainTrend = res || []
      if (lineChart) {
        let xData = []
        let yData = []
        trainTrend.forEach(v=>{
          xData.push(v.date)
          yData.push(v.num)
        })
        lineOption.series[0].data = yData
        lineOption.xAxis.data = xData
        lineOption.series[0].symbol = (xData.length === 1) ? 'circle' : 'none'
        if (type === 'training') {
          lineOption.series[0].areaStyle.normal.color =  new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            { offset: 0, color: "#fff" },
            { offset: 1, color: "#12B37D" }
          ])
          lineOption.series[0].lineStyle.normal.color = '#12B37D'
        } else {
          lineOption.series[0].areaStyle.normal.color =  new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            { offset: 0, color: "#fff" },
            { offset: 1, color: "#4661F4" }
          ])
          lineOption.series[0].lineStyle.normal.color = '#4661F4'
        }
        lineChart.clear()
        lineChart.setOption(lineOption, true)
      }
    })
  },
  getStudyTrend () {
    let params = this.data.queryForm
    const {selectIndex , type } = this.data
    let url = ''
    if(selectIndex === '0'){
        url = 'qryStudentsTrend'
        params = {...this.data.queryForm,appFlag:1}
    }else if (selectIndex === '1'){
        url = 'qryStudyNumTrend'
    }else{
        url = 'qryCompletedCourseTrend'
    }
    app.api.post({
      url: url,
      data: params
    }).then(res=>{
      console.log(res,'=====');
      const studyTrend = res || []
      if (lineChart) {
        let xData = []
        let yData = []
        studyTrend.forEach(v=>{
          xData.push(v.date)
          yData.push(v.num)
        })
        lineOption.series[0].data = yData
        lineOption.xAxis.data = xData
        lineOption.series[0].symbol = (xData.length === 1) ? 'circle' : 'none'
        if (type === 'training') {
          lineOption.series[0].areaStyle.normal.color =  new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            { offset: 0, color: "#fff" },
            { offset: 1, color: "#12B37D" }
          ])
          lineOption.series[0].lineStyle.normal.color = '#12B37D'
        } else {
          lineOption.series[0].areaStyle.normal.color =  new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            { offset: 0, color: "#fff" },
            { offset: 1, color: "#4661F4" }
          ])
          lineOption.series[0].lineStyle.normal.color = '#4661F4'
        }
        lineChart.clear()
        lineChart.setOption(lineOption, true)
      }
    })
  },
  getTrainDetail (postData = {}) {
    const params = this.data.queryForm
    const { currentPage } = this.data 
    app.api.post({
      url: 'qryTrainingDetail',
      data: {...params,...postData,currentPage:this.data.currentPage,pageSize:15}
    }).then(res=>{
      let { list } = this.data
      currentPage === 1 ? (list = res.list) : list.push(...res.list)
      this.setData({ list,hasFixed:false })
      console.log(res,'=====');
    })
  },
  getStudyDetail (postData = {}) {
    const params = this.data.queryForm
    const { currentPage } = this.data 
    app.api.post({
      url: 'qryStudyDetail',
      data: {...params,...postData,currentPage:this.data.currentPage,pageSize:15}
    }).then(res=>{
      let { list } = this.data
      currentPage === 1 ? (list = res.list) : list.push(...res.list)
      this.setData({ list,hasFixed:false })
      console.log(res,'=====');
    })
  },
  activeList () {
    const params = Object.assign({indexType: this.data.type}, this.data.queryForm)
    app.api.post({
      url: 'qryStudyToTalNum',
      data: params
    }).then(res => {
      this.setData({
        bannerInfo: res.data,
        list: res.stuData ? res.stuData : [],
        activityBoardTrendRespList: res.activityBoardTrendRespList
      })
      if (lineChart) {
        lineOption.series[0].data = res.activityBoardTrendRespList[0].ydata
        lineOption.xAxis.data = res.activityBoardTrendRespList[0].xdata
        console.log(res.activityBoardTrendRespList[0].xdata.length === 1)
        lineOption.series[0].symbol = (res.activityBoardTrendRespList[0].xdata.length === 1) ? 'circle' : 'none'
        console.log(this.data.type)
        if (this.data.type === 'training') {
          lineOption.series[0].areaStyle.normal.color =  new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            { offset: 0, color: "#fff" },
            { offset: 1, color: "#12B37D" }
          ])
          lineOption.series[0].lineStyle.normal.color = '#12B37D'
        } else {
          lineOption.series[0].areaStyle.normal.color =  new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            { offset: 0, color: "#fff" },
            { offset: 1, color: "#4661F4" }
          ])
          lineOption.series[0].lineStyle.normal.color = '#4661F4'
        }
        lineChart.clear()
        lineChart.setOption(lineOption, true)
      }
      if (funnelChart) {
        let levelOnePercent = res.transformDetailResp.levelOne > 0 ? 100 : 0
        let levelTwoPercent = levelOnePercent > 0 ? Math.floor(((res.transformDetailResp.levelTwo)*100)/res.transformDetailResp.levelOne) : 0
        let levelThreePercent = levelOnePercent > 0 ? Math.floor(((res.transformDetailResp.levelThree)*100)/res.transformDetailResp.levelOne) : 0
        let levelFourPercent = levelOnePercent > 0 ? Math.floor(((res.transformDetailResp.levelFour)*100)/res.transformDetailResp.levelOne) : 0
        let levelFivePercent = levelOnePercent > 0 ? Math.floor(((res.transformDetailResp.levelFive)*100)/res.transformDetailResp.levelOne) : 0
        let funnelArr1 = [{value: levelOnePercent, name: '学习主页'}, {value: levelTwoPercent, name: '课程详情页'}, {value: levelThreePercent, name: '章节详情页'}, {value: levelFourPercent, name: '演练详情页'}, {value: levelFivePercent, name: '通关详情页'}]
        let funnelArr2 = [{value: res.transformDetailResp.levelOne, name: '学习主页'}, {value: res.transformDetailResp.levelTwo, name: '课程详情页'}, {value: res.transformDetailResp.levelThree, name: '章节详情页'}, {value: res.transformDetailResp.levelFour, name: '演练详情页'}, {value: res.transformDetailResp.levelFive, name: '通关详情页'}]
        funnelOption.series[0].data = funnelArr1
        funnelOption.series[1].data = funnelArr2
        funnelChart.clear()
        funnelChart.setOption(funnelOption, true)
      }
      if (categoryChart) {
        let categoryArr = [{
            value:res.transformDetailResp.levelFive,
            itemStyle:{
              normal:{color:'#52CCA3'}
          }}, 
          {
            value:res.transformDetailResp.levelFour,
            itemStyle:{
              normal:{color:'#69EEC2'}
          }},
          {
            value:res.transformDetailResp.levelThree,
            itemStyle:{
              normal:{color:'#C2F7E5'}
          }},
          {
            value:res.transformDetailResp.levelTwo,
            itemStyle:{
              normal:{color:'#69EEC2'}
          }},
          {
            value:res.transformDetailResp.levelOne,
            itemStyle:{
              normal:{color:'#5DCFA9'}
          }}]
          categoryOption.series[0].data = categoryArr
          console.log(categoryOption.series[0].data)
          categoryChart.clear()
          categoryChart.setOption(categoryOption, true)
      }
    })
  },
  // 培训活动的明细
  getTrainActiveList () {
    const params = Object.assign({}, this.data.queryForm)
    const { currentPage } = this.data 
    app.api.post({
      url: 'report_activity_activityCoachingDetail',
      data: {...params,currentPage:this.data.currentPage,pageSize:15}
    }).then(res => {
      let arr = res || []
      arr.forEach((v) => {
        v.handler = '查看排名'
        v.nameAndTime = [v.name, v.validityTime]
      })
      console.log(res)
      let { list } = this.data
      currentPage === 1 ? (list = arr) : list.push(...arr)
      this.setData({
        list: list
      })
      console.log(this.data.list,'list=======')
    })
  },
  handler (e) {
    console.log(e.detail.row.id, '233')
    wx.navigateTo({
      url: `/myself/pages/my-training/rank/rank?coachingSessionId=${e.detail.row.id}`
    })
  },
  detailHandler(e) {
    console.log(e.detail.row,'row========');
    // console.log(e.detail.row.id, 'detail')
    const {id = '' , name = '' , validityTime = ''} = e.detail.row
    wx.navigateTo({
      url: `/echarts/pages/myself/exam-detail/examDetail?id=${id}&name=${name}&time=${validityTime}`
    })
  },
  // 训练的场景明细
  getTrainSceneList (postData = {}) {
    const params = Object.assign({}, this.data.queryForm)
    const { currentPage } = this.data 
    app.api.post({
      url: 'qryScenarioTrainingDetail',
      data: {...params,...postData,currentPage:this.data.currentPage,pageSize:15}
    }).then(res => {
      let { sceneList } = this.data
      currentPage === 1 ? (sceneList = res.list) : sceneList.push(...res.list)
      this.setData({
        sceneList: sceneList
      })
    })
  },
  getcurrentOrgDetail () {
    app.api.get({
      url: 'cpic_org_getOrgLevel',
      data: { id: app.globalData.userInfo.orgId }
    }).then(res => {
      this.data.query.bankName = res.bank.id === app.globalData.userInfo.orgId ? '' : res.bank.orgName
      this.data.queryForm.levelOneOrgId = res.bank ? res.bank.id : ''
      this.data.bankindex = res.bank.id === app.globalData.userInfo.orgId ? 0 : ''

      this.data.query.bankBranchName = (res.branch && res.branch.id) === app.globalData.userInfo.orgId ? '' : (res.branch && res.branch.orgName)
      this.data.queryForm.levelTwoOrgId = res.branch ? res.branch.id : ''
      this.data.branchidindex = (res.branch && res.branch.id) === app.globalData.userInfo.orgId ? 0 : ''
      
      this.data.query.bankSubBranchName = (res.subBranch && res.subBranch.id) === app.globalData.userInfo.orgId ? '' : (res.subBranch && res.subBranch.orgName)
      this.data.queryForm.levelThreeOrgId = res.subBranch ? res.subBranch.id : ''
      this.data.subBranchindex = (res.subBranch && res.subBranch.id) === app.globalData.userInfo.orgId ? 0 : ''

      this.data.query.bankWorkstationName = res.site ? '' : ''
      this.data.queryForm.levelFourOrgId = res.site ? res.site.id : ''
      this.data.siteindex = res.site ? 0 : ''
      this.setData({
        query: this.data.query,
        queryForm: this.data.queryForm,
        bankindex: this.data.bankindex,
        branchidindex: this.data.branchidindex,
        subBranchindex: this.data.subBranchindex,
        siteindex: this.data.siteindex
      })
    })
  },
  bankChange: function(e) {
    // let toggleUrl
    // if (this.data.queryForm.roleType === 'student') {
    //   toggleUrl = 'userAccessableBank_getAccessableBankOrgChildrenByParentId'
    // } else {
    //   toggleUrl = 'cpic_internal_org_getChildrenByParentId'
    // }
    this.data.queryForm.levelOneOrgId = this.data.bankidList[e.detail.value]
    this.data.params.parentId = this.data.bankidList[e.detail.value]
    this.setData({
      bankindex: e.detail.value,
      params: this.data.params
    })
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: this.data.params
    }).then(res => {
      if (res.length > 0) {
        this.data.branchList = []
        this.data.branchidList = []
        res.map(item => {
            this.data.branchList.push(item.orgName)
            this.data.branchidList.push(item.id)
          })
      } else {
        this.data.branchList = []
        this.data.subBranchList = []
        this.data.siteList = []
      }
      this.data.queryForm.levelTwoOrgId = ''
      this.data.queryForm.levelThreeOrgId = ''
      this.data.queryForm.levelFourOrgId = ''
      this.setData({
        branchList: this.data.branchList,
        subBranchList: this.data.subBranchList,
        siteList: this.data.siteList,
        branchidList: this.data.branchidList,
        branchidindex: '',
        subBranchindex: '',
        siteindex: '',
        queryForm: this.data.queryForm
      }, () => {
        console.log('赋值成功')
        this.timeAndOrgChange()
        if (this.data.typeName === '考试') {
          this.getTrainActiveList()
        }
      })
    })
  },
  branchChange: function(e) {
    // let toggleUrl
    // if (this.data.queryForm.roleType === 'student') {
    //   toggleUrl = 'userAccessableBank_getAccessableBankOrgChildrenByParentId'
    // } else {
    //   toggleUrl = 'cpic_internal_org_getChildrenByParentId'
    // }
    this.data.queryForm.levelTwoOrgId = this.data.branchidList[e.detail.value]
    this.data.params.parentId = this.data.branchidList[e.detail.value]
    this.setData({
      branchidindex: e.detail.value,
      params: this.data.params
    })
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: this.data.params
    }).then(res => {
      if (res.length > 0) {
        this.data.subBranchList = []
        this.data.subBranchidList = []
        res.map(item => {
            this.data.subBranchList.push(item.orgName)
            this.data.subBranchidList.push(item.id)
          })
      } else {
        this.data.subBranchList = []
        this.data.siteList = []
      }
      this.data.queryForm.levelThreeOrgId = ''
      this.data.queryForm.levelFourOrgId = ''
      this.setData({
        queryForm: this.data.queryForm,
        subBranchindex: '',
        siteindex: '',
        subBranchList: this.data.subBranchList,
        siteList: this.data.siteList,
        subBranchidList: this.data.subBranchidList
      }, () => {
        this.timeAndOrgChange()
        if (this.data.typeName === '考试') {
          this.getTrainActiveList()
        }
      })
    })
  },
  subBranchChange: function(e) {
    // let toggleUrl
    // if (this.data.queryForm.roleType === 'student') {
    //   toggleUrl = 'userAccessableBank_getAccessableBankOrgChildrenByParentId'
    // } else {
    //   toggleUrl = 'cpic_internal_org_getChildrenByParentId'
    // }
    console.log(e, this.data.subBranchList)
    this.data.queryForm.levelThreeOrgId = this.data.subBranchidList[e.detail.value]
    this.data.params.parentId = this.data.subBranchidList[e.detail.value]
    this.setData({
      subBranchindex: e.detail.value,
      params: this.data.params
    })
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgChildrenByParentId',
      data: this.data.params
    }).then(res => {
      if (res.length > 0) {
        this.data.siteList = []
        this.data.siteidList = []
        res.map(item => {
            this.data.siteList.push(item.orgName)
            this.data.siteidList.push(item.id)
          })
      } else {
        this.data.siteList = []
      }
      this.data.queryForm.levelFourOrgId = ''
      this.setData({
        queryForm: this.data.queryForm,
        siteindex: '',
        siteList: this.data.siteList,
        siteidList: this.data.siteidList
      }, () => {
        this.timeAndOrgChange()
        if (this.data.typeName === '考试') {
          this.getTrainActiveList()
        }
      })
    })
  },
  siteChange: function(e) {
    this.data.queryForm.levelFourOrgId = this.data.siteidList[e.detail.value]
    this.setData({
      siteindex: e.detail.value,
      queryForm: this.data.queryForm
    })
    this.timeAndOrgChange()
    if (this.data.typeName === '考试') {
      this.getTrainActiveList()
    }
  },
  // 开始时间
  bindstartDateChange: function(e) {
    this.setData({
      startdate: e.detail.value
    })
    this.data.queryForm.startDate = e.detail.value
    this.setData({
      queryForm: this.data.queryForm
    })
    this.timeAndOrgChange()
    if (this.data.typeName === '考试') {
      this.getTrainActiveList()
    }
  },
  // 结束时间
  bindendDateChange: function(e) {
    this.setData({
      enddate: e.detail.value
    })
    this.data.queryForm.endDate = e.detail.value
    this.setData({
      queryForm: this.data.queryForm
    })
    this.timeAndOrgChange()
    if (this.data.typeName === '考试') {
      this.getTrainActiveList()
    }
  },
  // 时间或者组织改变，重新查询列表
  timeAndOrgChange() {
    this.setData({
      currentPage:1
    })
    const {typeName} = this.data
    if (typeName === '学习') {
      this.getStudyStatus()
      this.getStudyTrend()
      this.getStudyDetail()
    }else if (typeName === '训练'){
      this.getTrainStatus()
      this.getTrainTrend()
      this.getTrainDetail()
      this.getTrainSceneList()
    }
  },
  // 获取所有银行
  getAllBankList () {
    app.api.post({
      url: 'userAccessableBank_getAccessableBank',
      data: {}
    }).then(res => {
      // 银行
      let bankList = []
      let bankidList = []
      if (res.length > 0) {
        res.map(item => {
          bankList.push(item.orgName)
          bankidList.push(item.id)
        })
      }
      this.setData({
        bankList: bankList,
        bankidList: bankidList,
      })
    })
  },
  // 客户经理下的组织
  getAdminOrgList () {
    app.api.get({
      url: 'cpic_internal_org_getTreeByParentId',
      data: { orgId: this.data.orgId }
    }).then(res => {
      console.log(res)
      // 银行
      let bankList = []
      let bankidList = []
      if (res.length > 0) {
        res.map(item => {
          bankList.push(item.orgName)
          bankidList.push(item.id)
        })
      }
      this.setData({
        bankList: bankList,
        bankidList: bankidList,
      })
    })
  }
})